<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件


use think\facade\Config;

if (!function_exists('get_middle_str')) {
    /**
     * 获取两个字符串中间的字符
     * @param $str
     * @param $leftStr
     * @param $rightStr
     * @return bool|string
     */
    function get_middle_str($str, $leftStr, $rightStr)
    {
        $left  = strpos($str, $leftStr);
        $right = strpos($str, $rightStr, $left);
        if ($right < $left || $left < 0) {
            return '';
        }
        return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
    }
}


if (!function_exists('format_size')) {
    /**
     * 格式化文件大小单位
     * @param $size
     * @param string $delimiter
     * @return string
     */
    function format_size($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 5; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}


if (!function_exists('setting')) {
    /**
     * 设置相关助手函数
     * @param string $name
     * @param null $value
     * @return array|bool|mixed|null
     */
    function setting($name = '', $value = null)
    {
        if ($value === null && is_string($name)) {
            //获取一级配置
            if ('.' === substr($name, -1)) {
                $result = Config::get(substr($name, 0, -1));
                if (count($result) == 0) {
                    //如果文件不存在，查找数据库
                    $result = get_database_setting(substr($name, 0, -1));
                }

                return $result;
            }
            //判断配置是否存在或读取配置
            if (0 === strpos($name, '?')) {
                $result = Config::has(substr($name, 1));
                if (!$result) {
                    //如果配置不存在，查找数据库
                    if ($name && false === strpos($name, '.')) {
                        return [];
                    }

                    if ('.' === substr($name, -1)) {

                        return get_database_setting(substr($name, 0, -1));
                    }

                    $name    = explode('.', $name);
                    $name[0] = strtolower($name[0]);

                    $result = get_database_setting($name[0]);
                    if ($result) {
                        $config = $result;
                        // 按.拆分成多维数组进行判断
                        foreach ($name as $val) {
                            if (isset($config[$val])) {
                                $config = $config[$val];
                            } else {
                                return null;
                            }
                        }

                        return $config;

                    }
                    return $result;
                }

                return $result;
            }

            $result = Config::get($name);
            if (!$result) {
                $result = get_database_setting($name);
            }
            return $result;
        }
        return Config::set($name, $value);
    }

}

if (!function_exists('get_database_setting')) {
    function get_database_setting($name)
    {
        $result = [];
        $group  = \app\common\model\SettingGroup::where('code', $name)->find();
        if ($group) {
            $result = [];
            foreach ($group->setting as $key => $setting) {
                $key_setting = [];
                foreach ($setting->content as $content) {
                    $key_setting[$content['field']] = $content['content'];
                }
                $result[$setting->code] = $key_setting;
            }
        }

        return $result;
    }
}

/**
 * 过滤html和img
 */
if (!function_exists('trimall')) {

    function trimall($str)
    {
        $qian = array(" ", "　", "\t", "\n", "\r", "&nbsp;", "&", "nbsp", ";");
        $str = str_replace($qian, '', $str);
        preg_replace('/<\s+img[^>]+>/i', '', $str);
        preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', '', $str);

        return preg_replace("/<img.*?>/si", "", $str);
    }
}

// 生成订单号
if (!function_exists('createOrderNo')) {
    function createOrderNo()
    {
        try {

            $order_no =
                date('d')
                . random_int(0, 9)
                . date('m')
                . random_int(0, 9)
                . date('y')
                . random_int(0, 9)
                . date('i')
                . random_int(0, 9)
                . date('H')
                . random_int(0, 9)
                . date('s')
                . random_int(0, 9);

            $msg = 'success';
        } catch (\Exception $e) {
            $order_no = '';
            $msg      = $e->getMessage();
        }
        if (empty($order_no)) {
            new  Exception($msg);
        }

        return $order_no;
    }
}

// curl post 请求
if (!function_exists('requestPost')) {

    function requestPost($url, $data, $ssl = true)
    {
        //curl完成
        $curl = curl_init();
        //设置curl选项
        curl_setopt($curl, CURLOPT_URL, $url); //URL
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 FirePHP/0.7.4';
        curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); //user_agent，请求代理信息
        curl_setopt($curl, CURLOPT_AUTOREFERER, true); //referer头，请求来源
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); //设置超时时间
        //SSL相关
        if ($ssl) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //禁用后cURL将终止从服务端进行验证
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); //检查服务器SSL证书中是否存在一个公用名(common name)。
        }
        // 处理post相关选项
        curl_setopt($curl, CURLOPT_POST, true); // 是否为POST请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // 处理请求数据
        // 处理响应结果
        curl_setopt($curl, CURLOPT_HEADER, false); //是否处理响应头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //curl_exec()是否返回响应结果

        // 发出请求
        $response = curl_exec($curl);
        if (false === $response) {
            echo '<br>', curl_error($curl), '<br>';
            return false;
        }
        curl_close($curl);
        return $response;
    }
}
// 检查目录是否存在， 不存在就创建
if (!function_exists('mkdir_chmod')) {

    function mkdir_chmod($path, $mode = 0777)
    {
        if (is_dir($path)) {
            return true;
        }
        $result = mkdir($path, $mode, true);
        if ($result) {
            $path_arr = explode('/', $path);
            $path_str = '';
            foreach ($path_arr as $val) {
                $path_str .= $val . '/';
                $a = chmod($path_str, $mode);
            }
        }
        return $result;
    }
}

if (!function_exists('arr_encode')) {
    function arr_encode($arr)
    {
        return json_encode($arr,true);
    }
}

/**
 * 隐藏手机号中间4位
 */
if (!function_exists('yc_phone')) {
    function yc_phone($str)
    {
        $str = $str;
        $resstr = substr_replace($str, '****', 3, 4);
        return $resstr;
    }
}
/**
 * 查找字符串中的数字
 */
if (!function_exists('findNum')) {

    function findNum($str = '')
    {
        $str = trim($str);
        if (empty($str)) {
            return [];
        }
        $reg = '/\d+/'; //匹配数字的正则表达式
        preg_match_all($reg, $str, $result);
        if (is_array($result) && !empty($result)) {
            return $result[0];
        }
        return [];
    }
}
